package cn.ytr.crm.service.impl;

import cn.ytr.crm.domain.Department;
import cn.ytr.crm.mapper.DepartmentMapper;
import cn.ytr.crm.mapper.EmployeeMapper;
import cn.ytr.crm.query.QueryObject;
import cn.ytr.crm.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DepartmentServiceImpl implements IDepartmentService{

	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private EmployeeMapper employeeMapper;

	/**
	 * 增加或保存部门
	 */
	@Override
	public void saveOrUpate(Department department) {
		if (department.getId() != null) {
			departmentMapper.updateByPrimaryKey(department);
		} else {
			departmentMapper.insert(department);
		}
	}

	/**
	 * 删除部门
	 */
	@Override
	public void delete(Long id) {
		departmentMapper.deleteByPrimaryKey(id);
		//删除部门后，还要把员工表里该部门下的员工的 deptId 清空
		employeeMapper.updateDeptIdByDeptId(null, id);
	}

	/**
	 * 获取单个部门
	 */
	@Override
	@Transactional(readOnly=true)
	public Department get(Long id) {
		Department department = departmentMapper.selectByPrimaryKey(id);
		return department;
	}

	/**
	 * 获取所有部门
	 */
	@Override
	@Transactional(readOnly=true)
	public List<Department> listAll() {
		List<Department> list = departmentMapper.selectAll();
		return list;
	}

	/**
	 * 高级查询所有部门
	 */
	@Override
	@Transactional(readOnly=true)
	public PageInfo query(QueryObject qo) {
		/*Integer count = departmentMapper.selectForCount(qo);
		if (count < 1 || count == null) {
			return new PageResult(qo.getPageSize());
		} else {
			List<Department> list = departmentMapper.selectForList(qo);
			return new PageResult(qo.getCurrentPage(), count, list, qo.getPageSize());
		}*/

		//改用分页插件 pageHelper
		PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
		List<Department> list = departmentMapper.selectForList(qo);
		PageInfo pageInfo = new PageInfo(list);
		return pageInfo;

	}

}
